calcAIPWest <- function(outcome, dat, assg = "sb", exa.str = "gender + phq1mdddx", cov.str = "pssi1_tot + age + phq1tot + fas1tot + stroopINTtscore1 + lm1_t1recallSCALED + lm2_t1recallSCALED"){
  
  dat.p.out <- cbind(dat, outcome = dat[, outcome], ps = ps.vec)
  
  ## for Complete Randomization, allocate treatments and set propensity scores to 0.5:
  if(assg == "cr"){
    dat.p.out$condition <- sample(c("memory", "anagrams"), nrow(dat), replace = TRUE)
    dat.p.out$ps <- .5
  }
  ## one mean imputation:
  dat.p.out[which(is.na(dat.p.out$stroopINTtscore1)), "stroopINTtscore1"] <- mean(dat.p.out$stroopINTtscore1, na.rm = TRUE)

  ffff <- as.formula(paste("outcome ~ ", exa.str, " + ", cov.str))
  g.tr.out <- gam(ffff, data = dat.p.out[dat.p.out$condition == "memory",], maxit = 100, bf.maxit = 100)
  g.co.out <- gam(ffff, data = dat.p.out[dat.p.out$condition == "anagrams",], maxit = 100, bf.maxit = 100)
  pred.co.as.treated <- predict.gam(g.tr.out, newdata = dat.p.out[dat.p.out$condition == "anagrams",])
  pred.tr.as.control <- predict.gam(g.co.out, newdata = dat.p.out[dat.p.out$condition == "memory",])
  
  ate.contribs <- array(NA, nrow(dat.p.out))
  contrib.idx <- 0
  for(i in row.names(dat)){
    contrib.idx <- contrib.idx + 1
    tmp <- dat.p.out[i,]
    
    if(tmp$condition == "memory"){
      ate.contribs[contrib.idx] <- (1*tmp$outcome/tmp$ps) - ((1-tmp$ps)/(tmp$ps*(1-tmp$ps)))*((1-tmp$ps)*g.tr.out$fitted[names(g.tr.out$fitted) == i] + tmp$ps*pred.tr.as.control[names(pred.tr.as.control) == i])
    }
    if(tmp$condition == "anagrams"){
      ate.contribs[contrib.idx] <- (tmp$outcome/(1-tmp$ps)) - ((1-tmp$ps)/(tmp$ps*(1-tmp$ps)))*((1-tmp$ps)*pred.co.as.treated[names(pred.co.as.treated) == i] + tmp$ps*g.co.out$fitted[names(g.co.out$fitted) == i])
    }
  }
    
  ate.aipw <- mean(ate.contribs)

  rmse <- sqrt(mean((c(g.tr.out$fitted.values-dat.p.out[dat.p.out$condition == "memory", outcome], g.co.out$fitted.values-dat.p.out[dat.p.out$condition == "anagrams", outcome]))^2))
    
  return(list(ate.aipw = ate.aipw, rmse = rmse))
}
